using System;
using System.Collections;
using System.Web.UI;
using Sedna.Core.Globalization;

namespace Sedna.Core.Controller.Configurations
{
	/// <summary>
	/// Summary description for String2StringKeyDataGridColumnDataTranslator.
	/// </summary>
	public class String2StringKeyDataTranslator : IDataTranslator
	{

		private IDictionary value2key;
		private string defaultKey;
		private Type enumType;
		private IMessageManager messageManager;
		private IDataTranslator next = null;

		public IDictionary Value2key
		{
			set { value2key = value; }
		}

		public string DefaultKey
		{
			set { defaultKey = value; }
		}

		public Type EnumType
		{
			set { enumType = value; }
		}

		public IMessageManager MessageManager
		{
			set { messageManager = value; }
		}

		public IDataTranslator Next
		{
			set { next = value; }
		}

		public object Translate(Control control, object value)
		{
			return Translate(control, value, null);
		}

		public object Translate(Control control, object value, Type targetType)
		{
			string key = GetKey(control, value);
			if(messageManager == null)
			{
				return key;
			}
			else
			{
				return messageManager.GetMessage(key, value!=null?value.ToString():String.Empty);
			}
		}

		private string GetKey(Control control, object value)
		{
			if(value2key == null)
			{
				return defaultKey;
			}
			
			string key = value == null ? null : (string)value2key[GetStringValue(value)];

			if(key!=null)
			{
				return key;
			}
			if(next != null)
			{
				key = (string)next.Translate(control, value);
			}
			
			return key!=null?key:defaultKey;
		}

		private string GetStringValue(object value)
		{
			if(value == null)
			{
				return null;
			}
			if(enumType == null)
			{
				return value.ToString();
			}
			return Enum.GetName(enumType, value);
		}

	}
}
